package com.njbtd.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @ClassName PrimaryDataSource
 * @Description TODO
 * @Author leolinzc
 * @Date 24.5.6 13:34
 * @Version 1.0
 */
@Configuration
@MapperScan(basePackages = {
        "com.njbtd.mapper.primary"
}, sqlSessionFactoryRef = "primarySqlSessionFactory")
public class PrimaryDataSource {

    /**
     * @返回数据库的数据源
     * @return
     */
    @Primary
    @Bean(name="primarySource")
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DruidDataSource primaryDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    /**
     * @返回数据库的会话工厂
     * @param ds
     * @return
     * @throws Exception
     */
    @Bean(name = "primarySqlSessionFactory")
    @Primary
    public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primarySource") DataSource ds, MybatisProperties mybatisProperties) throws Exception{
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(ds);
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver()
                        .getResources("classpath:mapper/primary/*Mapper.xml")
        );
        SqlSessionFactory sqlSessionFactory = bean.getObject();
        sqlSessionFactory.getConfiguration()
                .setMapUnderscoreToCamelCase(mybatisProperties.getConfiguration().isMapUnderscoreToCamelCase());
        sqlSessionFactory.getConfiguration()
                .setJdbcTypeForNull(mybatisProperties.getConfiguration().getJdbcTypeForNull());
        return sqlSessionFactory;
    }
}
